<template>
	<view class="toast-box" v-if="isShow" :style="{opacity: isOpacity ? '1': '0', maxWidth:maxWidth+'rpx'}">
		{{ tmpConfig.text }}
	</view>
</template>

<script>
	function sleep(delay = 50) {
		return new Promise((resolve) => {
			setTimeout(() => {
				resolve()
			}, delay)
		})
	}
	export default {
		data() {
			return {
				config: {
					text: '',
					delay: 1500
				},
				isShow: false,
				isOpacity: true,
				tmpConfig: {}
			}
		},
		props: {
			maxWidth: {
				type: Number,
				default: 472
			}
		},
		methods: {
			show(options) {
				// 不将结果合并到this.config变量，避免多次调用u-toast，前后的配置造成混乱
				this.tmpConfig = uni.$u.deepMerge(this.config, options)
				// 清除定时器
				this.clearTimer()
				this.isShow = true
				this.isOpacity = true

				this.timer = setTimeout(async () => {
					this.isOpacity = false
					await sleep(500)
					this.isShow = false
				}, this.tmpConfig.delay)
			},
			clearTimer() {
				this.isShow = false
				// 清除定时器
				clearTimeout(this.timer)
				this.timer = null
			}
		}
	}
</script>

<style lang="scss" scoped>
	.toast-box {
		position: fixed;
		inset: 0;
		z-index: 10099;
		padding: 20rpx 34rpx;
		width: max-content;
		height: fit-content;
		box-sizing: border-box;
		max-width: 472rpx;
		border-radius: 10rpx;
		background: #000000bf;
		color: #ffffff;
		text-align: center;
		font-family: "Source Han Sans CN";
		font-size: 28rpx;
		font-style: normal;
		font-weight: 400;
		line-height: 30rpx;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		transition: all 0.5s ease-in-out;
		opacity: 1;
	}
</style>